package org.kim;

import org.kim.command.AccountCommand;
import org.kim.command.BookCommandProxy;
import org.kim.core.StorageCache;
import org.kim.core.Logger;
import org.kim.exception.CustomUncaughtExceptionHandler;
import org.kim.exception.ServiceException;
import org.kim.pojo.Account;
import org.kim.utils.CommandUtils;
import org.kim.utils.Constants;
import org.kim.utils.FileUtils;
import org.kim.utils.Md5Utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;

public class Main {

    public static void init() throws ClassNotFoundException {
        System.out.println("loading data from storage........");
        FileUtils.createStorageDict();
        FileUtils.loadDataFromStorage();
        System.out.println("load data done...................\n");
    }


    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ServiceException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
        CommandUtils.printHelpInfo();
        init();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("$");
            String userInput = scanner.nextLine();
            userInput = userInput.replace("$", "").trim();
            if (!CommandUtils.commandValidate(userInput)) {
                CommandUtils.printHelpInfo();
                continue;
            }
            String[] strs = CommandUtils.parseInput(userInput);
            String operationType = strs[0];
            if (userInput.equals("exit")) {
                break;
            }
            AccountCommand accountCommand = new AccountCommand();
            BookCommandProxy bookCommandProxy = new BookCommandProxy();
            switch (operationType) {
                case "register":
                    try {
                        String registerResult = accountCommand.register(strs);
                        Logger.info(registerResult);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    break;
                case "login":
                    String loginResult = null;
                    try {
                        loginResult = accountCommand.login(strs);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Logger.info(loginResult);
                    break;
                default:
                    String result = null;
                    result = bookCommandProxy.action(operationType + "Book", strs);
                    Logger.info(result);
                    break;
            }
        };
        Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
    }
}

